package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

import com.itheima.app.exception.BusinessException;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Sound;
import com.itheima.domain.mongo.SoundUser;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.SoundService;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.SoundVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Component
public class PeachBlossomManager {

    @DubboReference
    private SoundService soundService;

    @DubboReference
    private UserInfoService userInfoService;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer webServer;

    // 发送语音
    public void sendBlossom(MultipartFile soundFile) throws IOException {

        //1.上传文件到FDFS上
        //获取文件后缀名
        String filename = soundFile.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = fastFileStorageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), suffix, null);
        //获取链接
        String soundUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //创建Sound对象，并设置属性
        Sound sound = new Sound();
        sound.setSoundUrl(soundUrl);
        sound.setUserId(UserHolder.get().getId());
        sound.setReceived(false);
        sound.setCreated(System.currentTimeMillis());
        sound.setText("一段神秘的语音");
        soundService.saveOrUpdate(sound);
    }


    //接受语音
    public SoundVo receiveSound() {
        //查询当前可获取数量
        String today = cn.hutool.core.date.DateUtil.today();
        long minDate = cn.hutool.core.date.DateUtil.parseDateTime(today + " 00:00:00").getTime();
        long maxDate = cn.hutool.core.date.DateUtil.parseDateTime(today + " 23:59:59").getTime();
        Integer remainingTimes = 10 - soundService.getCount(UserHolder.get().getId(), minDate,maxDate);
        //随机获取语音
        if (remainingTimes <= 0) {
            SoundVo soundVo = new SoundVo();
            soundVo.setRemainingTimes(0);
            return soundVo;
        }
        List<Sound> sounds = soundService.find(UserHolder.get().getId());
        //查询用户信息
        if (CollectionUtil.isEmpty(sounds)){
            throw new BusinessException(ErrorResult.error().builder().errMessage("无数据").build());
        }
        Sound sound = sounds.get(0);
        UserInfo userInfo = userInfoService.findById(sound.getUserId());
        //封装结果返回
        SoundVo soundVo = SoundVo.init(userInfo, sound, remainingTimes);
        //接受成功后将信息更新
        saveSoundUserInfo(sound);
        updateSound(sound);
        return soundVo;
    }

    // 修改语音
    private void updateSound(Sound sound) {
        sound.setReceived(true);
        sound.setReceiveUserId(UserHolder.get().getId());
        soundService.saveOrUpdate(sound);
    }

    // 保存用户信息
    private void saveSoundUserInfo(Sound sound) {
        SoundUser soundUser = new SoundUser();
        soundUser.setUserId(UserHolder.get().getId());
        soundUser.setSid(sound.getSid());
        soundUser.setSendUserId(sound.getUserId());
        soundUser.setToday(System.currentTimeMillis());
        soundService.saveSoundUser(soundUser);
    }
}
